package com.steven.ourcontest.login.helper

import android.content.Context
import android.content.Intent
import com.steven.ourcontest.chat.helper.MessageHelper
import com.steven.ourcontest.main.view.MainActivity
import com.steven.ourcontest.net.websocket.WebSocketAndroidClient
import com.tencent.mmkv.MMKV

object LoginController {
    private val kv = MMKV.defaultMMKV()

    const val CODE_TIME = 30 * 60 * 1000L//验证码过期时长ms
    private const val KEY_IS_LOGIN = "key_is_login"
    private const val KEY_LAST_SEND_CODE_TIME = "key_last_send_code_time"
    private const val KEY_LAST_SEND_CODE = "key_last_send_code"
    private const val KEY_USER_ID = "key_user_id"
    private const val KEY_USER_TYPE = "key_user_type"
    private const val KEY_ICON_URL = "key_icon_url"

    var isLogin: Boolean
        set(value) {
            kv.putBoolean(KEY_IS_LOGIN, value)
        }
        get() = kv.getBoolean(KEY_IS_LOGIN, false)

    var lastSendCodeTime: Long
        set(value) {
            kv.putLong(KEY_LAST_SEND_CODE_TIME, value)
        }
        get() = kv.getLong(KEY_LAST_SEND_CODE_TIME, 0)

    var lastSendCode: Int
        set(value) {
            kv.putInt(KEY_LAST_SEND_CODE, value)
        }
        get() = kv.getInt(KEY_LAST_SEND_CODE, 0)

    var userId: Long
        set(value) {
            kv.putLong(KEY_USER_ID, value)
        }
        get() = kv.getLong(KEY_USER_ID, 0)

    var userType: String
        set(value) {
            kv.putString(KEY_USER_TYPE, value)
        }
        get() = kv.getString(KEY_USER_TYPE, "") ?: ""
    var iconUrl: String
        set(value) {
            kv.putString(KEY_ICON_URL, value)
        }
        get() = kv.getString(KEY_ICON_URL, "") ?: ""

    fun logout(context: Context) {
        isLogin = false
        lastSendCodeTime = 0
        lastSendCode = 0
        userId = 0
        userType = ""
        WebSocketAndroidClient.getInstance()?.disConnect()
        MessageHelper.messageUnReadMap.clear()
        MessageHelper.applyUnReadMap.clear()
        val intent = Intent(context, MainActivity::class.java)
        intent.putExtra("action", "logout")
        context.startActivity(intent)
    }
}